<?php defined('BASEPATH') OR exit('No direct script access allowed');

class manageWallpapers extends wsBackend
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model(array('wallpaper_model', 'category_model'));
    }

    public function index()
    {
        $data = array();

        $this->tpl->meta ['title'] = '壁纸管理 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '壁纸管理';
        $this->tpl->page_header_ = '';
        $this->tpl->breadcrumbs['Dashboard'] = 'active';
        $data['categories'] = $this->category_model->get_categoryDropDownTree();

        $data['featured_dropDown'] = array(
            '0' => '未推荐',
            '1' => '已推荐',
        );

        if ($this->input->get('q'))
            $filter['name'] = $this->input->get('q');
        if (isset($_GET['category']) && array_key_exists($this->input->get('category'), $data['categories']))
            $filter['category'] = (int)$this->input->get('category');
        if (isset($_GET['featured']) && array_key_exists($_GET['featured'], $data['featured_dropDown']))
            $filter['featured'] = $_GET['featured'];

        $filter['show_disabled'] = true;
        $filter['bypath'] = false;
        $config['uri_segment'] = 4;
        $data['offset'] = $filter['offset'] = $this->uri->segment($config['uri_segment']);
        $config['base_url'] = preg_replace('/' . $this->config->item('url_suffix') . '$/ix', '', admin_url('manageWallpapers/index'));
        $config['per_page'] = $filter['per_page'] = $this->config->item('items_per_page');
        if (!empty($_GET)) {
            $get_method = '/?' . http_build_query($this->input->get());
            $config['suffix'] = $this->config->item('url_suffix') . $get_method;
            $config['first_url'] = $config['base_url'] . $get_method;
        } else {
            $config['suffix'] = $this->config->item('url_suffix');
        }
        $this->tpl->page_header_ = $config['total_rows'] = $this->wallpaper_model->getWallpapers($filter + array('count' => true));

        $config['use_page_numbers'] = FALSE;
        $this->load->library('pagination');
        $this->pagination->initialize($config);

        $data['pagination'] = $this->pagination->create_links();
        $data['wallpapers'] = $this->wallpaper_model->getWallpapers($filter);
        $this->load->helper('date');
        $this->tpl->contents [] = $this->tpl->fetch('contents/manageWallpapers', $data);
        $this->tpl->render();
    }

    public function save()
    {
        $wall = $this->input->post('wall');
        if ($wall) {
            $update_data = $tags_data = array();
            foreach ($wall as $wall_id => $w) {
                $wallpaper = $this->wallpaper_model->getWallpaperByID($wall_id);
                if(!$wallpaper)
                    continue;
                $md5 = $this->wallpaper_model->get_wallpaper(array(
                    'category_slug' => $wallpaper->cFullSlug,
                    'wallpaper_slug' => $wallpaper->wallpaper_slug,
                    'wallpaper_hash' => $wallpaper->wallpaper_hash,
                    'md5' => true,
                ));
                delete_md5($md5);
                $update_data[] = array(
                    'wallpaper_seq_id' => $wall_id,
                    'wallpaper_name' => $w['wallpaper_name'],
                    'wallpaper_slug' => $w['wallpaper_slug'],
                    'category_seq_id' => $w['category_seq_id'],
                    'wallpaper_status' => (isset($w['wallpaper_status']) && $w['wallpaper_status'] ? 1 : 0),
                    'wallpaper_featured' => (isset($w['wallpaper_featured']) ? 1 : 0),
                    'wallpaper_approved' => (isset($w['wallpaper_approved']) ? 1 : 0),
                    'wallpaper_crop_position' => $w['wallpaper_position'],
                    'wallpaper_date_modified' => date('Y-m-d H:i:s'),
                );
                $this->wallpaper_model->removeWallpaperTags($wall_id);
                $this->wallpaper_model->removeWallpaperPath($wall_id);
                $tags = explode(',', $w['wallpaper_tags']);
                $tags = array_filter($tags);
                if (!empty($tags)) {
                    foreach ($tags as $tag) {
                        $tags_data[] = array(
                            'tag_name' => url_title_no_space($tag,true,'-'),
                            'wallpaper_seq_id' => $wall_id
                        );
                    }
                }
                $this->wallpaper_model->insert_path_single($wall_id, $w['category_seq_id']);
            }
            if (!empty($tags_data))
                $this->wallpaper_model->insertTags($tags_data, true);
            $this->wallpaper_model->update($update_data, false, 'wallpaper_seq_id');
            return true;
        }
    }

    public function delete($id = '', $offset = '')
    {
        $wallpaper = $this->wallpaper_model->getWallpaperByID($id);
        if (!$wallpaper) {
            $this->session->set_flashdata('ERROR', '壁纸ID有问题');
            redirect(admin_url('manageWallpapers/index/' . $offset));
        }
        $md5 = $this->wallpaper_model->get_wallpaper(array(
            'category_slug' => $wallpaper->cFullSlug,
            'wallpaper_slug' => $wallpaper->wallpaper_slug,
            'wallpaper_hash' => $wallpaper->wallpaper_hash,
            'md5' => true,
        ));
        delete_md5($md5);
        $this->wallpaper_model->deleteByIDs($id);
        $this->session->set_flashdata('SUCCESS', '删除成功');
        redirect(admin_url('manageWallpapers/index/' . $offset));
    }

    public function delete_bulk()
    {
        $id = $this->input->post('wallpaper_id');
        $offset = $this->input->post('offset');
        if (!$id) {
            $this->session->set_flashdata('ERROR', '壁纸ID有问题');
            redirect(admin_url('manageWallpapers/index/' . $offset));
        }
        $this->wallpaper_model->deleteByIDs($id);
        $this->session->set_flashdata('SUCCESS', '删除成功');
        redirect(admin_url('manageWallpapers/index/' . $offset));
    }

    public function add()
    {
        $data = array();

        $this->tpl->meta ['title'] = '上传壁纸 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '上传壁纸';
        $this->tpl->page_header_ = '';
        $this->tpl->breadcrumbs['Manage Wallpaper'] = admin_url('manageWallpapers');
        $this->tpl->breadcrumbs['Add'] = 'active';
        $data['categories'] = $this->category_model->get_categoryDropDownTree();
        $data['wallpaper'] = false;
        $this->load->library('form_validation');

        $this->form_validation->set_rules('wallpaper_name', 'Wallpaper Name', 'required');
        $this->form_validation->set_rules('user_seq_id', 'User Seq ID', 'required');
        $this->form_validation->set_rules('category_seq_id', 'Category Seq ID', 'required');
        $this->form_validation->set_rules('wallpaper_status', 'Wallpaper Status', 'required');

        $data['image'] = false;
        $temp_image = $this->input->post('temp_image_path');
        if ($temp_image && file_exists(FCPATH . $temp_image))
            $data['image'] = $temp_image;


        $upload_data = false;

        if (!empty($_POST) && (!$data['image'] || (isset($_FILES['wallpaper_image_path']['error']) && $_FILES['wallpaper_image_path']['error'] == UPLOAD_ERR_OK))) {
            $config['upload_path'] = FULL_TEMP . DS . $this->user->get_id();
            if (!is_dir($config['upload_path']))
                mkdir($config['upload_path'], 0777, true);
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = MAX_SIZE;
            $config['overwrite'] = TRUE;
            if ($this->config->item('minimum_width'))
                $config['min_width'] = $this->config->item('minimum_width');
            if ($this->config->item('minimum_height'))
                $config['min_height'] = $this->config->item('minimum_height');
            $this->load->library('upload', $config);
            if (!$this->upload->do_upload('wallpaper_image_path')) {
                $this->tpl->error[] = $this->upload->display_errors();
            } else {
                $upload_data = $this->upload->data();
                $data['image'] = FULL_TEMP_RAW . DS . $this->user->get_id() . DS . $upload_data['file_name'];
            }
        }

        if ($this->input->post('wallpaper_name') && !$this->input->post('wallpaper_slug'))
            $_POST['wallpaper_slug'] = url_title_no_space($this->input->post('wallpaper_name'),'-',true);

        if ($this->form_validation->run() && empty($this->tpl->error) && $data['image']) {

            if (!array_key_exists($this->input->post('category_seq_id'), $data['categories'])) {
                $this->tpl->error[] = '错误的分类ID：分类不存在';
            }

            if (empty($this->tpl->error)) {

                //Move File
                $dateFolder = date('Y/m/d/');
                $new_path = ORIGINALS_FOLDER_WF . DS . $dateFolder;
                if (!is_dir($new_path))
                    mkdir($new_path, 0777, true);
                $new_path .= basename($data['image']);
                $imageInfo = GetImageInfo_($data['image'], 'default');
                $move_file_name = $this->image_workshop->move_file(FCPATH . $data['image'], FCPATH . $new_path);
                $insert_data = array(
                    'wallpaper_name' => $this->input->post('wallpaper_name'),
                    'wallpaper_slug' => $this->input->post('wallpaper_slug'),
                    'user_seq_id' => $this->input->post('user_seq_id'),
                    'category_seq_id' => $this->input->post('category_seq_id'),
                    'wallpaper_image_path' => $dateFolder . $move_file_name,
                    'wallpaper_width' => $imageInfo['width'],
                    'wallpaper_height' => $imageInfo['height'],
                    'wallpaper_status' => ($this->input->post('wallpaper_status') ? 1 : 0),
                    'wallpaper_featured' => ($this->input->post('wallpaper_featured') ? 1 : 0),
                    'wallpaper_approved' => ($this->input->post('wallpaper_approved') ? 1 : 0),
                    'wallpaper_description' => (strip_tags($this->input->post('wallpaper_description')) != '' ? $this->input->post('wallpaper_description') : NULL),
                    'wallpaper_date_created' => date('Y:m:d H:i:s'),
                    'wallpaper_metatitle' => $this->input->post('wallpaper_metatitle'),
                    'wallpaper_metadescription' => $this->input->post('wallpaper_metadescription'),
                    'wallpaper_metakeywords' => $this->input->post('wallpaper_metakeywords'),
                    'wallpaper_author' => $this->input->post('wallpaper_author'),
                    'wallpaper_author_site' => $this->input->post('wallpaper_author_site'),
                    'wallpaper_crop_position' => in_array($this->input->post('wallpaper_crop_position'), $this->image_workshop->positions) ? $this->input->post('wallpaper_crop_position') : 'MM',
                );

                $insert_id = $this->wallpaper_model->insert($insert_data);
                $hash = $this->hashids->encrypt($insert_id);
                $update = array(
                    'wallpaper_hash' => $hash,
                );
                $this->wallpaper_model->update($update, array('wallpaper_seq_id' => $insert_id));

                $this->load->library(array('colors_extract', 'colors_tool'));
                $colors = $this->colors_extract->get_Color(ORIGINALS_FOLDER . DS . $insert_data['wallpaper_image_path']);
                if ($colors) {
                    $bulk_colors = array();
                    foreach ($colors as $color => $count_percentage) {
                        $hsl = colors_tool::hexToHsl($color);
                        $bulk_colors[] = array(
                            'wallpaper_seq_id' => $insert_id,
                            'count' => $count_percentage,
                            'hex_code' => $color,
                            'hue' => $hsl['H'],
                            'saturation' => $hsl['S'],
                            'lightness' => $hsl['L'],
                        );
                    }
                    if (!empty($bulk_colors))
                        $this->wallpaper_model->insert_colors($bulk_colors,true);
                }


                $tags = explode(',', $this->input->post('wallpaper_tags'));
                $tags = array_filter($tags);
                if (!empty($tags)) {
                    $insert_tags = array();
                    foreach ($tags as $t) {
                        $t = trim($t);
                        $insert_tags[] = array(
                            'wallpaper_seq_id' => $insert_id,
                            'tag_name' => url_title_no_space($t,'-'),
                        );
                    }
                    if (!empty($insert_tags))
                        $this->wallpaper_model->insertTags($insert_tags, true);
                }
                $this->session->set_flashdata('SUCCESS', '壁纸上传成功');
                if (isset($_POST['s_e']))
                    redirect(admin_url('manageWallpapers/edit/' . $insert_id));
                if (isset($_POST['s_c']))
                    redirect(admin_url('manageWallpapers/'));
                if (isset($_POST['s_n']))
                    redirect(admin_url('manageWallpapers/add'));
                redirect(admin_url('manageWallpapers/'));
            }
        }

        $this->tpl->contents [] = $this->tpl->fetch('contents/manageWallpapers_update', $data);
        $this->tpl->render();
    }

    public function edit($id = '', $offset = '')
    {
        if (!$id) {
            $this->session->set_flashdata('ERROR', '壁纸ID有问题');
            redirect(admin_url('manageWallpapers/' . $offset));
        }

        $data = array();
        $this->tpl->meta ['title'] = '编辑壁纸 - ' . $this->config->item('site_name');
        $this->tpl->meta ['description'] = '';
        $this->tpl->meta ['keywords'] = '';
        $this->tpl->page_header = '编辑壁纸 - ' . $id;
        $this->tpl->page_header_ = '';
        $this->tpl->breadcrumbs['Manage Wallpaper'] = admin_url('manageWallpapers');
        $this->tpl->breadcrumbs['Edit - ' . $id] = 'active';
        $data['categories'] = $this->category_model->get_categoryDropDownTree();
        $data['wallpaper'] = $this->wallpaper_model->getWallpaperByID($id);
        if (!$data['wallpaper']) {
            $this->session->set_flashdata('ERROR', '壁纸ID有问题');
            redirect(admin_url('manageWallpapers/' . $offset));
        }
        $this->load->library('form_validation');

        $this->form_validation->set_rules('wallpaper_name', 'Wallpaper Name', 'required');
        $this->form_validation->set_rules('user_seq_id', 'User Seq ID', 'required');
        $this->form_validation->set_rules('category_seq_id', 'Category Seq ID', 'required');
        $this->form_validation->set_rules('wallpaper_status', 'Wallpaper Status', 'required');

        $data['image'] = $og_image = ORIGINALS_FOLDER_WF . DS . $data['wallpaper']->wallpaper_image_path;
        $temp_image = $this->input->post('temp_image_path');
        if ($temp_image && file_exists(FCPATH . $temp_image))
            $data['image'] = $temp_image;


        $upload_data = false;

        if (!empty($_POST) && (!$data['image'] || (isset($_FILES['wallpaper_image_path']['error']) && $_FILES['wallpaper_image_path']['error'] == UPLOAD_ERR_OK))) {
            $config['upload_path'] = FULL_TEMP . DS . $this->user->get_id();
            if (!is_dir($config['upload_path']))
                mkdir($config['upload_path'], 0777, true);
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = MAX_SIZE;
            $config['overwrite'] = TRUE;
            if ($this->config->item('minimum_width'))
                $config['min_width'] = $this->config->item('minimum_width');
            if ($this->config->item('minimum_height'))
                $config['min_height'] = $this->config->item('minimum_height');
            $this->load->library('upload', $config);
            if (!$this->upload->do_upload('wallpaper_image_path')) {
                $this->tpl->error[] = $this->upload->display_errors();
            } else {
                $upload_data = $this->upload->data();
                $data['image'] = FULL_TEMP_RAW . DS . $this->user->get_id() . DS . $upload_data['file_name'];
            }
        }

        if ($this->input->post('wallpaper_name') && !$this->input->post('wallpaper_slug'))
            $_POST['wallpaper_slug'] = url_title_no_space($this->input->post('wallpaper_name'),'-',true);

        if ($this->form_validation->run() && empty($this->tpl->error) && $data['image']) {

            if (!array_key_exists($this->input->post('category_seq_id'), $data['categories'])) {
                $this->tpl->error[] = '错误的分类ID：分类不存在';
            }

            if (empty($this->tpl->error)) {
                $move_file_name = false;
                $dateFolder = date('Y/m/d/');
                if ($data['image'] != $og_image) {
                    //Move File
                    $new_path = ORIGINALS_FOLDER_WF . DS . $dateFolder;
                    if (!is_dir($new_path))
                        mkdir($new_path, 0777, true);
                    $new_path .= basename($data['image']);
                    $imageInfo = GetImageInfo_($data['image'], 'default');
                    $move_file_name = $this->image_workshop->move_file(FCPATH . $data['image'], FCPATH . $new_path);
                }

                $update_data = array(
                    'wallpaper_name' => $this->input->post('wallpaper_name'),
                    'wallpaper_slug' => $this->input->post('wallpaper_slug'),
                    'user_seq_id' => $this->input->post('user_seq_id'),
                    'category_seq_id' => $this->input->post('category_seq_id'),
                    'wallpaper_status' => ($this->input->post('wallpaper_status') ? 1 : 0),
                    'wallpaper_featured' => ($this->input->post('wallpaper_featured') ? 1 : 0),
                    'wallpaper_approved' => ($this->input->post('wallpaper_approved') ? 1 : 0),
                    'wallpaper_description' => (strip_tags($this->input->post('wallpaper_description')) != '' ? $this->input->post('wallpaper_description') : NULL),
                    'wallpaper_date_modified' => date('Y:m:d H:i:s'),
                    'wallpaper_metatitle' => $this->input->post('wallpaper_metatitle'),
                    'wallpaper_metadescription' => $this->input->post('wallpaper_metadescription'),
                    'wallpaper_metakeywords' => $this->input->post('wallpaper_metakeywords'),
                    'wallpaper_author' => $this->input->post('wallpaper_author'),
                    'wallpaper_author_site' => $this->input->post('wallpaper_author_site'),
                    'wallpaper_crop_position' => in_array($this->input->post('wallpaper_crop_position'), $this->image_workshop->positions) ? $this->input->post('wallpaper_crop_position') : 'MM',
                );

                if ($move_file_name) {
                    $update_data['wallpaper_image_path'] = $dateFolder . $move_file_name;
                    $update_data['wallpaper_width'] = $imageInfo['width'];
                    $update_data['wallpaper_height'] = $imageInfo['height'];

                    $this->load->library(array('colors_extract', 'colors_tool'));
                    $colors = $this->colors_extract->get_Color(ORIGINALS_FOLDER . DS . $update_data['wallpaper_image_path']);
                    if ($colors) {
                        $bulk_colors = array();
                        foreach ($colors as $color => $count_percentage) {
                            $hsl = colors_tool::hexToHsl($color);
                            $bulk_colors[] = array(
                                'wallpaper_seq_id' => $id,
                                'count' => $count_percentage,
                                'hex_code' => $color,
                                'hue' => $hsl['H'],
                                'saturation' => $hsl['S'],
                                'lightness' => $hsl['L'],
                            );
                        }
                        $this->wallpaper_model->deleteWallColors($id);
                        if (!empty($bulk_colors))
                            $this->wallpaper_model->insert_colors($bulk_colors,true);
                    }
                }

                $this->wallpaper_model->update($update_data, array('wallpaper_seq_id' => $id));

                if ($this->input->post('category_seq_id') != $data['wallpaper']->category_seq_id) {
                    $this->wallpaper_model->removeWallpaperPath($id);
                    $this->wallpaper_model->insert_path_single($id, $this->input->post('category_seq_id'));
                }

                $tags = explode(',', $this->input->post('wallpaper_tags'));
                $tags = array_filter($tags);
                if (!empty($tags)) {
                    $insert_tags = array();
                    foreach ($tags as $t) {
                        $t = trim($t);
                        $insert_tags[] = array(
                            'wallpaper_seq_id' => $id,
                            'tag_name' => url_title_no_space($t,'-'),
                        );
                    }
                    $this->wallpaper_model->removeWallpaperTags($id);

                    if (!empty($insert_tags))
                        $this->wallpaper_model->insertTags($insert_tags, true);
                }

                $md5 = $this->wallpaper_model->get_wallpaper(array(
                    'category_slug' => $data['wallpaper']->cFullSlug,
                    'wallpaper_slug' => $data['wallpaper']->wallpaper_slug,
                    'wallpaper_hash' => $data['wallpaper']->wallpaper_hash,
                    'md5' => true,
                ));
                delete_md5($md5);
                $this->session->set_flashdata('SUCCESS', '壁纸编辑成功');
                if (isset($_POST['s_e']))
                    redirect(admin_url('manageWallpapers/edit/' . $id));
                if (isset($_POST['s_c']))
                    redirect(admin_url('manageWallpapers/index/' . $offset));
                if (isset($_POST['s_n']))
                    redirect(admin_url('manageWallpapers/add'));
                redirect(admin_url('manageWallpapers/'));
            }
        }

        $this->tpl->contents [] = $this->tpl->fetch('contents/manageWallpapers_update', $data);
        $this->tpl->render();
    }

}
